﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections.Generic;
using System.Windows.Data;
using System.IO;
using System.Linq;
using Cinch;
using System.Windows.Threading;
using System.Configuration;


namespace Anata.Client
{
    /// <summary>
    /// </summary>
    public class LayananSelectViewModel : ViewModelBase
    {
        #region Data
        #region Data.Primitives
        private String filterKeyword = "";

        private bool isAllLoaded = false;
        private int pageLoaded = 0;
        private DispatcherTimer filterTimer;
        #endregion

        #region Data.Rules
        #endregion

        #region Data.VMs
        private DispatcherNotifiedObservableCollection<LayananThumbnailViewModel> layanans;
        private ICollectionView layanansCV;
        #endregion

        #region Data.Services
        private IViewAwareStatus viewAwareStatusService;
        private IMessageBoxService messageBoxService;
        private IUIVisualizerService uiVisualizerService;
        private IReferenceProvider referenceProvider;
        #endregion

        #endregion

        #region Constructor
        [ImportingConstructor]
        public LayananSelectViewModel(
            IMessageBoxService messageBoxService,
            IUIVisualizerService uiVisualizerService,
            IReferenceProvider referenceProvider)
        {
            #region Constructor.SetupServices
            this.messageBoxService = messageBoxService;
            this.uiVisualizerService = uiVisualizerService;
            //this.viewAwareStatusService = viewAwareStatusService;
            this.referenceProvider = referenceProvider;
            //this.viewAwareStatusService.ViewLoaded += ViewAwareStatusService_ViewLoaded;
            #endregion

            #region Constructor.SetupCommands
            FilterKeyUpCommand = new SimpleCommand<Object, Object>(CanExecuteFilterKeyUpCommand, ExecuteFilterKeyUpCommand);
            ListMouseLeftButtonUpCommand = new SimpleCommand<Object, Object>(CanExecuteListMouseLeftButtonUpCommand, ExecuteListMouseLeftButtonUpCommand);
            #endregion

            #region Constructor.SetupDataWrappers
            #endregion

            #region Constructor.SetupValidationRules
            #endregion

            #region Constructor.SetupVMs
            layanans = new DispatcherNotifiedObservableCollection<LayananThumbnailViewModel>();
            layanansCV = CollectionViewSource.GetDefaultView(layanans);
            #endregion

            Mediator.Instance.Register(this);

            #region Constructor.Filter
            filterTimer = new DispatcherTimer();
            filterTimer.Interval = TimeSpan.FromMilliseconds(
                Int32.Parse(ConfigurationManager.AppSettings["FilterResponsiveness"].ToString()));
            filterTimer.Tick += new EventHandler(LazyFilterCallback);
            #endregion

            LoadLayanans();
        }
        #endregion

        #region Public Properties
        #region Public.Commands
        public SimpleCommand<Object, Object> FilterKeyUpCommand { get; private set; }
        public SimpleCommand<Object, Object> ListMouseLeftButtonUpCommand { get; private set; }
        #endregion

        #region Public.ViewMode
        #endregion

        #region Public.Data
        /// <summary>
        /// </summary>
        static PropertyChangedEventArgs filterKeywordChangeArgs =
            ObservableHelper.CreateArgs<LayananSelectViewModel>(x => x.FilterKeyword);
        public String FilterKeyword
        {
            get { return filterKeyword; }
            set
            {
                filterKeyword = value;
                NotifyPropertyChanged(filterKeywordChangeArgs);
                LazyFilter();
            }
        }
        #endregion

        #region Public.CachedCollection
        #endregion

        #region Public.DataVMs
        /// <summary>
        /// Loaded Konsumen
        /// </summary>
        static PropertyChangedEventArgs layanansChangeArgs =
            ObservableHelper.CreateArgs<LayananSelectViewModel>(x => x.Layanans);

        public DispatcherNotifiedObservableCollection<LayananThumbnailViewModel> Layanans
        {
            get { return layanans; }
            set
            {
                layanans = value;
                NotifyPropertyChanged(layanansChangeArgs);
            }
        }
        /// <summary>
        /// Loaded Konsumen
        /// </summary>
        static PropertyChangedEventArgs layanansCVChangeArgs =
            ObservableHelper.CreateArgs<LayananSelectViewModel>(x => x.LayanansCV);

        public ICollectionView LayanansCV
        {
            get { return layanansCV; }
            set
            {
                layanansCV = value;
                NotifyPropertyChanged(layanansCVChangeArgs);
            }
        }
        #endregion
        #endregion

        #region Command Handlers
        /// <summary>
        /// </summary>
        private bool CanExecuteFilterKeyUpCommand(Object args)
        {
            return true;
        }
        /// <summary>
        /// </summary>
        private void ExecuteFilterKeyUpCommand(Object args)
        {
            LazyFilter();
        }

        /// <summary>
        /// </summary>
        private bool CanExecuteListMouseLeftButtonUpCommand(Object args)
        {
            return true;
        }
        /// <summary>
        /// </summary>
        private void ExecuteListMouseLeftButtonUpCommand(Object args)
        {
            if (layanansCV.CurrentPosition > -1)
            {
                CloseActivePopUpCommand.Execute(true);
            }
        }
        #endregion

        #region IViewStatusAwareInjectionAware Members
        #endregion
        
        #region Private Methods
        #region PrivateMethods.ViewLoaded
        private void ViewAwareStatusService_ViewLoaded()
        {
            LoadLayanans();
        }
        #endregion

        #region PrivateMethods.Filter
        private void LazyFilter()
        {
            filterTimer.Stop();
            filterTimer.Start();
        }
        private void LazyFilterCallback(object sender, EventArgs e)
        {
            Console.WriteLine("stopped typing, filtering with keyword: " + filterKeyword);
            filterTimer.Stop();
            if (filterKeyword != "")
            {
                layanansCV.Filter = new Predicate<object>(LazyFilterPredicate);
            }
            else
            {
                layanansCV.Filter = null;
            }
        }
        private bool LazyFilterPredicate(object row)
        {
            LayananThumbnailViewModel ltvm = row as LayananThumbnailViewModel;
            return (ltvm.Nama.ToLower().Contains(filterKeyword.ToLower()));
        }
        #endregion

        #region PrivateMethods.Loader
        /// <summary>
        /// loader
        /// </summary>
        private void LoadLayanans()
        {
            referenceProvider.LazyFetchLayanans(pageLoaded, PostLoadLayanans);
        }

        /// <summary>
        /// post loader
        /// </summary>
        private void PostLoadLayanans(List<LayananThumbnailViewModel> ltvms)
        {
            //rekursif sampai semua diload
            int pageSize = Int32.Parse(ConfigurationManager.AppSettings["LazyLoadPageSize"].ToString());
            foreach (var item in ltvms)
            {
                layanans.Add(item);
            }

            if (ltvms.Count != pageSize)
            {
                //basis
                //sudah habis, done loading
                isAllLoaded = true;
            }
            else
            {
                //rekurens
                ++pageLoaded;
                LoadLayanans();
            }
        }
        #endregion
        #endregion
    }
}
//        #region Constructor
//        [ImportingConstructor]
//        public LayananSelectViewModel(
//            IMessageBoxService messageBoxService,
//            IUIVisualizerService uiVisualizerService,
//            IReferenceProvider referenceProvider)
//        {
//            #region Constructor.SetupServices
//            this.messageBoxService = messageBoxService;
//            this.uiVisualizerService = uiVisualizerService;
//            #endregion

//            #region Constructor.SetupCommands
//            #endregion

//            #region Constructor.SetupDataWrappers
//            #endregion

//            //cachedListOfDataWrappers =
//            //    DataWrapperHelper.GetWrapperProperties<LayananCabangViewModel>(this);

//            #region Constructor.SetupValidationRules
//            #endregion

//            #region Constructor.SetupCollections
//            LayananCabangFilter = new LayananCabangFilterViewModel(
//                messageBoxService,
//                uiVisualizerService);
//            LayananCabangFilter.layananselectCommand = new SimpleCommand<Object, Object>(CanExecutelayananselectCommand, ExecutelayananselectCommand);
//            #endregion
//        }
//        #endregion

//        #region Public Properties

//        #region Public.Commands
//        #endregion

//        #region Public.ViewMode
//        #endregion

//        #region Public.Data
//        #endregion

//        #region Public.CachedCollection
//        #endregion

//        #region Public.DataVM
//        /// <summary>
//        /// </summary>
//        static PropertyChangedEventArgs selectedLayananCabangChangeArgs =
//            ObservableHelper.CreateArgs<LayananSelectViewModel>(x => x.SelectedLayananCabang);

//        public LayananCabangViewModel SelectedLayananCabang
//        {
//            get { return selectedLayananCabang; }
//            set
//            {
//                selectedLayananCabang = value;
//                NotifyPropertyChanged(selectedLayananCabangChangeArgs);
//            }
//        }
//        /// <summary>
//        /// </summary>
//        static PropertyChangedEventArgs layananCabangFilterChangeArgs =
//            ObservableHelper.CreateArgs<LayananSelectViewModel>(x => x.LayananCabangFilter);

//        public LayananCabangFilterViewModel LayananCabangFilter
//        {
//            get { return layananCabangFilter; }
//            set
//            {
//                layananCabangFilter = value;
//                NotifyPropertyChanged(layananCabangFilterChangeArgs);
//            }
//        }
//        #endregion

//        #endregion

//        #region Command Handlers
//        /// <summary>
//        /// </summary>
//        private bool CanExecutelayananselectCommand(Object args)
//        {
//            return true;
//            //return LayananCabangFilter.layanansCV.CurrentPosition > -1;
//        }
//        /// <summary>
//        /// </summary>
//        private void ExecutelayananselectCommand(Object args)
//        {
//            Console.WriteLine("masuk level atas select layanancabang");
//            SelectedLayananCabang = (LayananCabangViewModel) LayananCabangFilter.layanansCV.CurrentItem;
//            if (SelectedLayananCabang != null)
//            {
//                CloseActivePopUpCommand.Execute(true);
//            }
//        }

//        #endregion

//        #region IViewStatusAwareInjectionAware Members

//        //public void InitialiseViewAwareService(IViewAwareStatus viewAwareStatusService)
//        //{
//        //    this.ViewAwareStatusService = viewAwareStatusService;
//        //    //this.ViewAwareStatusService.ViewLoaded += ViewAwareStatusService_ViewLoaded;
//        //}
//        #endregion
        
//        #region Private Methods
//        //private void ViewAwareStatusService_ViewLoaded()
//        //{
//        //    LoadedKonsumenFilterViewModel = new KonsumenFilterViewModel(
//        //        uiVisualizerService,
//        //        ViewAwareStatusService);
//        //}

//        #endregion
//    }

//}
